<template>
    <div class="repair">
        <van-form
            show-error
            scroll-to-error
            label-width="25vw"
            @submit="onSubmit"
            @failed="onFailed" 
        >
            <my-title>盘花租借</my-title>
            <FieldPopupCascader 
                :field="gsy_ex100"
                @update:field="gsy_ex100Change"
                name="gsy_ex100" 
                label="墓区" 
                :options="columns1" 
                confirmType="selectedOptions"
                :readonly="isReadonly" 
            />
            <FieldPopupPicker 
                v-if="gsy_ex100"
                :field="gcr_mainid"
			    @update:field="gcr_mainidChange"
                :required="true"
                name="gcr_mainid" 
                label="墓穴编号" 
                :columns="columns2" 
			    confirmType="selectedOptions"
                :readonly="isReadonly" 
            />
            <van-field 
                v-model="formData.gcr_ex1" 
                :readonly="isReadonly"
                required
                center
                name="gcr_ex1" 
                label="联系人"
                placeholder="联系人" 
                :rules="[{ required: true, message: '请填写联系人' }]"
            />
            <van-field 
                v-model="formData.gcr_ex2" 
                :readonly="isReadonly"
                required
                center
                type="number" 
                maxlength="11"
                name="gcr_ex2" 
                label="联系电话"
                placeholder="联系电话" 
                :rules="[{ required: true, message: '请填写联系电话' },{ validator: isPhone, message: '请填写正确的联系电话' }]"
            />
            <!-- <FieldUploader 
                v-model="formData.gcr_ex4"
                v-model:all-form-data="formData"
                :readonly="isReadonly"
                :required="true"
                :maxCount="9" 
                uploadText="报修图片" 
                uploadField="gcr_ex4"
            /> -->
            <FixedButton v-if="!isReadonly" native-type="submit">提交</FixedButton>
        </van-form>
    </div>
</template>

<script lang="ts" setup>
    import { ref, reactive, markRaw, onBeforeMount } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    import { showDialog, showLoadingToast, closeToast, showFailToast  } from 'vant'
    import FixedButton from '@/components/FixedButton.vue'
    import FieldPopupPicker from '@/components/FieldPopupPicker.vue'
    import FieldPopupDatePicker from '@/components/FieldPopupDatePicker.vue'
    import FieldPopupTimePicker from '@/components/FieldPopupTimePicker.vue'
    import FieldPopupEsign from '@/components/FieldPopupEsign.vue'
    import FieldPopupCascader from '@/components/FieldPopupCascader.vue'
    import FieldUploader from '@/components/FieldUploader.vue'
    import { saveCemeteryRepairApi, fileUploadBase64ExApi, idOrcApi, getRecordDetailsApi, getAareaApi, getCemeteryApi } from '@/apis'
    import { isPhone, compressImg, isCardID } from '@/utils/utils.js'
    import { useStore } from '@/store'
    
    const router = useRouter()
    const route = useRoute()
    const store = useStore()
    const isReadonly: boolean = route.query?.sh_id ? true : false
    
    const columns1: Ref<{
        text: string;
        value: string;
    }[]> = ref([
        // { text: '墓穴1', value: '墓穴1' },
        // { text: '墓穴2', value: '墓穴2' },
    ])
    const columns2: Ref<{
        text: string;
        value: string;
    }[]> = ref([
        // { text: '编号1', value: '编号1' },
        // { text: '编号2', value: '编号2' },
    ])
    
    const gsy_ex100Change = (val) => {
        gsy_ex100.value = ''
		val.forEach((item, index) => {
			if (val.length == (index+1)) {
				gsy_ex100.value += item.text
				formData.value.gsy_ex100 = item.value
			} else {
				gsy_ex100.value += item.text + '/'
			}
		})
        formData.value.gcr_mainid = ''
        gcr_mainid.value = ''
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0
        });
        columns2.value = []
        getCemeteryApi({
            areaId: formData.value.gsy_ex100,
            company: '海陵区凤栖园智慧墓园系统'
        }).then(res => {
            res.data[0]?.child.forEach((item, index) => {
                item.text = item.gm_ex6
                item.value = item.gm_id
            })
            columns2.value = res.data[0].child
        }).finally(() => {
            closeToast();
        })
    }
    const gcr_mainidChange = (val) => {
        gcr_mainid.value = val.text
        formData.value.gcr_mainid = val.value
    }
    const formData = ref({
        sh_ex1: '',
        sh_ex2: '',
        sh_ex5: '',
        sh_ex35: '',
        gcr_mainid: '',
        gcr_dat1: '',
        gcr_ex3: '',
        gcr_ex4: '',
        gsy_ex100: '',
        gcr_ex1: '',
        gcr_ex2: '',
    })
    const gsy_ex100: Ref<string> = ref('')
    const gcr_mainid: Ref<string> = ref('')

    const dataArr = reactive({
        gcr_ex4: [], //报修图片
    })
    
    onBeforeMount(async () => {
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0
        });
        getAareaApi({
            iszj: 'N',
            time: new Date().getTime().toString(),
            company: '海陵区凤栖园智慧墓园系统'
        }).then(res => {
			let forFun = (arr2) => {
				arr2.forEach((item, index) => {
					item.value = item.id
					item.text = item.text
					if (item.child.length > 0) {
						item.children = item.child
						forFun(item.children)
					}
				})
			}
			forFun(res[0].child)
            columns1.value = res[0].child
        }).finally(() => {
            closeToast();
        })
        if (isReadonly) {
            console.log('...........')
            // 获取数据
            getRecordDetailsApi({
                sh_id: route.query.sh_id
            }).then(res => {
                formData.value = res.data[0]
                if (formData.value.gcr_ex4) {
                    dataArr.gcr_ex4 = [{
                        url: formData.value.gcr_ex4,
                        isImage: true
                    }]
                }
            })
        }
    })
    const beforeDelete = (data) => {
        return (file, detail) => {
            let arr = formData.value[data].split(',')
            arr.splice(detail.index, 1)
            formData.value[data] = arr.join(',')
            return true
        }
    }
    const beforeRead = (file) => {
        console.log(file)
        if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
            showFailToast('请上传 jpg/png 格式图片');
            return false;
        }
        return true;
    }
    const afterRead = (imgField, isIdOrc = false) => {
        return file => {
            file.status = 'uploading';
            file.message = '上传中...';
            // 执行压缩图片并上传
            let obj = new compressImg(file, afterRead2, imgField, isIdOrc, file )
            // console.log(obj)
            // console.log(obj.getMyf())
            // console.log(obj.getMyfb())
            // console.log(obj.myf)
            // console.log(obj.myfb)
        }
    }
    // 组件方法 获取 流
    const afterRead2 = (imgField, isIdOrc, file, obj) => {
        // failed done 
        // file.status = 'uploading';
        // file.message = '上传中...';
        // file.file: 文件 file.content: base64图片
        console.log(file)
        // let f = new FormData()
        // f.append('file', file.file)
        fileUploadBase64ExApi({
            data: obj,
            sCode: 'kmxbyg'
        }).then(res => {
            // file.status = 'done';
            // file.message = '上传完成';
            console.log(res)

            if (imgField == 'sh_ex36' || imgField == 'sh_ex37') {
                // 拍照识按钮要显示不能设置maxCount=1，不然上传一张图就没了按钮
                if (dataArr[imgField].length > 1) {
                    dataArr[imgField].shift()
                }
                formData.value[imgField] = res[0].url
                // 用过拍照识别后续上传身份证都要进行idOrc验证信息
                if (isIdOrc) {
                    idOrcApi({
                        img: obj
                    }).then(res => {
                        if (res.idcard_number_type == 1) {
                            let obj = res.words_result

                            if (imgField == 'sh_ex36') {
                                formData.value.sh_ex1 = obj['姓名'].words
                                formData.value.sh_ex2 = obj['公民身份号码'].words
                                // formData.value.sh_ex3 = obj['性别'].words
                            } else if (imgField == 'sh_ex37') {
                                formData.value.sh_ex5 = obj['姓名'].words
                                formData.value.sh_ex35 = obj['公民身份号码'].words
                            }
                        } else {
                            throw new Error('身份证验证失败')
                        }
                        file.status = 'done';
                        file.message = '上传完成';
                        
                    }).catch(err => {
                        console.log(err)
                        showFailToast('识别失败')
                        file.status = 'done';
                        file.message = '上传完成';
                    })
                } else {
                    file.status = 'done';
                    file.message = '上传完成';
                }

            } else {
                // formData.value[imgField] = res[0].url
                if (formData.value[imgField]) {
                    formData.value[imgField] = formData.value[imgField].concat(',', res[0].url)
                } else {
                    formData.value[imgField] = formData.value[imgField].concat(res[0].url)
                }
                file.status = 'done';
                file.message = '上传完成';
            }
            
        }).catch(err => {
            file.status = 'failed';
            file.message = '上传失败';
            console.log(dataArr[imgField])
            dataArr[imgField].pop()
            showFailToast('上传失败')
            console.log(err)
        })
    }

    const onFailed = (value) => {
        showDialog({
            title: '提示',
            message: value.errors[0].message
        })
    }
    const onSubmit = async (value) => {
        showDialog({
            title: '提示',
            message: '提交成功！',
        }).then(() => {
            router.push('/')                         
        });

        // showLoadingToast({
        //     message: '加载中...',
        //     forbidClick: true,
        //     duration: 0
        // });
        // saveCemeteryRepairApi({
        //     // data: JSON.stringify(formData.value),
        //     ...formData.value,
        //     company: '海陵区凤栖园智慧墓园系统',
        //     dw: '海陵区凤栖园智慧墓园系统',
        // }).then(res => {
        //     closeToast();
        //     if (res[0].status == '+OK') {
        //         showDialog({
        //             title: '提示',
        //             message: '提交成功！',
        //         }).then(() => {
        //             router.push('/')                         
        //         });
        //     } else {
        //         showDialog({
        //             title: '提示',
        //             message: res[0].msg,
        //         })
        //     }
        // }).catch(err => {
        //     closeToast();
        //     showDialog({
        //         title: '提示',
        //         message: '网络异常，请稍后重试！',
        //     })
        // })
    }
</script>
<style lang="scss" scoped>
    .repair {
        height: 100vh;
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }
    :deep(.van-form) {
        // height: 550px;
        // height: 510px;
        flex: 1;
        overflow: scroll;
    }
    .uploader-box {
        border-bottom: 1px solid #999999;
        margin: 6px 15px;
        box-sizing: border-box;
        padding: 0px 0;
        height: 180px;
        overflow: hidden;
        img {
            width: 345px;
            height: 180px;
        }
        // 上传图片后图片大小
        :deep(.van-uploader__preview-image) {
            width: 345px;
            height: 180px;
        }
    }
    .my-card {
        background: #fff;
        border-bottom: 1px solid #efefef;
    }
    .card-price {
        text-align: right;
        font-size: 20px;
        font-weight: bold;
        padding: 10px;
        .card-price-span1 {
            font-size: 15px;
        }
        .card-price-span2 {
            display: inline-block;
            width: 90px;
        }
    }
</style>